<script setup>

import CardBox from "@/components/CardBox/index.vue";
import {useRouter} from "vue-router";
import {Download} from "@element-plus/icons-vue";
import {
  addAchievementApi, addMyPaperApplyApi, addPaperApplyApi,
  deleteAcademicOutputApi, deletePaperApplyApi,
  detailsAcademicOutputApi, detailsPaperApplyApi,
  downWallAcademicOutputApi,
  downWallActualOutPutApi, downWallPaperApplyApi,
  getAchievementListApi,
  getAllAchievementTypeApi, getAllPaperJournalApi, getMyPaperApplyApi, getNoMeStudentListApi, getPaperApplyListApi,
  getStudentListApi, getTeacherListApi,
  updateAcademicOutputApi, updateMyPaperApplyApi, updatePaperApplyApi,
  wallAcademicOutputApi,
  wallActualOutPutApi, wallPaperApplyApi
} from "@/api/school.js";
import useUserStore from "@/store/modules/user.js";
import {formatDateNoTime} from "../../../utils/index.js";

const {proxy} = getCurrentInstance();

const router = useRouter()
const userStore = useUserStore()
const state = reactive({
  studentList: [],
  selectData:[],
  formRules: {
    stuId: [
      {required: true, message: '请选择学生', trigger: 'change'},
    ],
    acTitle: [
      {required: true, message: '请输入论文名称', trigger: 'blur'},
    ],
    resultTypeName: [
      {required: true, message: '请输入期刊名称', trigger: 'blur'},
    ],
    teacherIds: [
      {required: true, message: '请选择指导老师', trigger: 'change'},
    ],
  },
  editForm: {
    id: '',
    stuId: '',
    acTitle: '',
    acFile: '',
  },
  achievementTypeList: [],
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  total: 0,
  title: '新增',
  ids: [],
})
const showDia1 = ref(false)
const selectable = (row) => ![].includes(row.id)
const handleAdd = async () => {
  showDia1.value = true
}

const handleEdit = async (id) => {
  // 获取详情
  const res = await detailsPaperApplyApi({id})
  if (res.code == 200) {
    state.editForm = res.data

    const data = {
      ids:res.data.memberIds
    }
    const res2 = await getNoMeStudentListApi(data)
    state.studentList = res2.data
    showDia1.value = true
    state.title = '编辑'
  }
}

const searchStudent = async (query) => {
  const res = await getStudentListApi({stuName: query})
  if (res.code == 200) {
    state.studentList = res.data
  }
}

const submitForm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      let res = ''
      if (state.editForm.id == '') {
        res = await addMyPaperApplyApi(state.editForm)
      } else {
        res = await updateMyPaperApplyApi(state.editForm)
      }

      if (res.code == 200) {
        proxy.$message.success('操作成功')
        handleClose()
        await getDataList()
      }
    }
  })
}

const getAllAchievementType = async () => {
  const res = await getAllPaperJournalApi()
  if (res.code == 200) {
    state.achievementTypeList = res.data
  }
}

const getDataList = async () => {
  if(state.queryParams.acTime){
    state.queryParams.startTime = state.queryParams.acTime[0]
    state.queryParams.endTime = state.queryParams.acTime[1]
  }
  const res = await getMyPaperApplyApi(state.queryParams)
  if (res.code == 200) {
    state.tableData = res.rows
    state.total = res.total
  }
}

const handleDelete = (id) => {
  proxy.$modal.confirm('是否删除该数据？').then(async () => {
    const res = await deletePaperApplyApi({id})
    if (res.code == 200) {
      proxy.$modal.msgSuccess("删除成功")
    }
    await getDataList()
  })
}

const handleClose = () => {
  showDia1.value = false
  state.editForm = {
    id: '',
    stuId: '',
    acTitle: '',
  }
  proxy.resetForm("formRef");
  state.title = '新增'
}

const resetSearch = () => {
  proxy.resetForm("queryRef");
  state.queryParams = {
    pageNum: 1,
    pageSize: 10,
  }
  getDataList()
}

const handleChecked = (id, checked) => {
  const index = state.ids.findIndex(item => item.id === id)
  if (index !== -1) {
    state.ids.splice(index, 1)
  } else {
    state.ids.push(id)
  }
}

const handleWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否上墙该数据？').then(async () => {
      const res = await wallPaperApplyApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}

const handleDownWall = () => {
  if (state.ids.length == 0) {
    proxy.$modal.msgError("请选择要操作的数据")
  } else {
    proxy.$modal.confirm('是否下墙该数据？').then(async () => {
      const res = await downWallPaperApplyApi({ids: state.ids})
      if (res.code == 200) {
        proxy.$modal.msgSuccess("操作成功")
        await getDataList()
      }
    })
  }
}

const handleApproval = () => {
  router.push("/approvalManagement/teacherApproval")
}

const changeStu = async (id) => {
  state.editForm.instructorTeacherId = ''
  // 获取教师列表
  const res = await getTeacherListApi({id})
  if (res.code == 200) {
    state.teacherList = res.data
  }
}

// 参与人员
const handleJoin = (outPutId) => {
  router.push({
    path: "paperJournalJoin",
    query: {
      outPutId
    }
  })
}

const getIsStudent = () => {
  return userStore.roles.includes('student')
}

const remoteMethod = async (val) => {
  state.loadding = true
  const data = {
    stuName:val
  }
  const res = await getNoMeStudentListApi(data)
  state.loadding = false
  state.studentList = res.data
}

const remoteMethod2 = async (val) => {
  state.loadding = true
  const data = {
    stuName:val
  }
  const res = await getStudentListApi(data)
  state.loadding = false
  state.studentList2 = res.data
}

// 导出
const handleExport = () => {
  if(state.selectData.length < 1){
    proxy.$modal.msgError("请选择需要导出的数据")
  }

  state.selectData.forEach(item => {
    proxy.download("/school/journalsOutput/export-word", {
      id: item.id
    },`${item.stuName}-${item.recognitionName}.docx`);
  })
}

const handleSelectionChange = (val) => {
  state.selectData = val
}

onMounted(() => {
  getAllAchievementType()
  getDataList()
   changeStu(userStore.stuId)
})
</script>

<template>
  <div class="outBox">
    <CardBox style="margin-bottom: 20px" title="筛选查询">
      <template #btn-cont>
        <el-button type="primary" @click="getDataList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </template>
      <template #content>
        <el-form :model="state.queryParams" label-width="80" inline="true" ref="queryRef">
<!--          <el-form-item label="第一作者">-->
<!--            <el-input v-model="state.queryParams.acTitle"/>-->
<!--          </el-form-item>-->
          <el-form-item label="发表时间">
            <el-date-picker
                v-model="state.queryParams.acTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                style="min-width: 180px"
            />
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="state.queryParams.acAudit" placeholder="请选择" style="min-width: 180px">
              <el-option label="待审核" :value="1"></el-option>
              <el-option label="审核通过" :value="2"></el-option>
              <el-option label="审核拒绝" :value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </CardBox>
    <CardBox title="数据列表">
      <template #btn-cont>
        <el-button type="primary" @click="handleExport">
          <el-icon>
            <Download/>
          </el-icon>
          <span>导出</span>
        </el-button>
        <el-button type="primary" @click="handleAdd">上传论文</el-button>
      </template>
      <template #content>
        <el-table :data="state.tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" :selectable="selectable" width="55">
<!--            <template #default="scope">-->
<!--              <el-checkbox v-model="scope.row.checked" @change="handleChecked(scope.row.id, scope.row.checked)"-->
<!--                           :disabled="scope.row.acAudit !== 2"/>-->
<!--            </template>-->
          </el-table-column>
          <el-table-column label="序号" type="index" width="50" align="center"/>
          <el-table-column prop="recognitionName" label="期刊/会议名称" align="center"/>
          <el-table-column prop="recognitionLevel" label="等级" align="center"/>
          <el-table-column prop="stuName" label="第一作者" align="center"/>
          <el-table-column prop="participants" label="其他作者" align="center">
            <template #default="scope">
              <span style="margin-right: 5px" v-for="(item,index) in scope.row.participants">{{ item.stuName }} <span v-if="index != scope.row.participants.length - 1">、</span></span>
            </template>
          </el-table-column>
          <el-table-column prop="acTitle" label="论文名称" align="center" width="200">
            <template #default="scope">
              <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="scope.row.acTitle"
                  placement="top"
              >
                <div>{{ scope.row.acTitle.substring(0, 10) }}</div>
              </el-tooltip>

            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="发表时间" align="center">
            <template #default="scope">
              {{ formatDateNoTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="acAudit" label="上传审核" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.acAudit == 1" type="info">待审核</el-tag>
              <el-tag v-if="scope.row.acAudit == 2" type="success">通过</el-tag>
              <el-tag v-if="scope.row.acAudit == 3" type="danger">未通过</el-tag>
            </template>
          </el-table-column>
<!--          <el-table-column prop="acWall" label="是否上墙" align="center">-->
<!--            <template #default="scope">-->
<!--              <el-tag v-if="scope.row.acWall == 1">未上墙</el-tag>-->
<!--              <el-tag v-else>已上墙</el-tag>-->
<!--            </template>-->
<!--          </el-table-column>-->

          <el-table-column prop="teachers" label="指导老师" align="center">
            <template #default="scope">
              <el-tag style="margin-right: 5px" v-for="item in scope.row.teachers">{{ item.teacherName }}</el-tag>
            </template>
          </el-table-column>

<!--          <el-table-column prop="academicTeacher" label="学业老师" align="center">-->
<!--            <template #default="scope">-->
<!--              <el-tag>{{ scope.row.academicTeacher }}</el-tag>-->
<!--            </template>-->
<!--          </el-table-column>-->

          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" link @click="handleEdit(scope.row.id)">详情查看/编辑</el-button>
              <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pageBox">
          <pagination
              v-show="state.total > 0"
              :total="state.total"
              v-model:page="state.queryParams.pageNum"
              v-model:limit="state.queryParams.pageSize"
              @pagination="getDataList()"
          />
        </div>
      </template>
    </CardBox>

    <el-dialog :title="state.title" v-model="showDia1" width="800" align-center>
      <div>
        <el-form label-width="140px" ref="formRef" :model="state.editForm" :rules="state.formRules">
          <el-row>
            <el-col :span="24">
              <el-form-item label="期刊/会议名称" prop="resultTypeName">
                <el-input v-model="state.editForm.resultTypeName" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="论文名称" prop="acTitle">
                <el-input v-model="state.editForm.acTitle" placeholder="请输入"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="第一作者">
<!--                {{ userStore.nickName }}-->
                <el-select
                    v-model="state.editForm.stuId"
                    placeholder="请选择"
                    style="width: 240px"
                    filterable
                    remote
                    :remote-method="remoteMethod2"
                    :loading="state.loadding"
                >
                  <el-option
                      v-for="item in state.studentList2"
                      :key="item.id"
                      :label="item.stuName + '-' + item.stuNum"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="其他作者" prop="memberIds">
                <el-select
                    v-model="state.editForm.memberIds"
                    multiple
                    placeholder="请选择"
                    style="width: 240px"
                    :multiple-limit="5"
                    filterable
                    remote
                    :remote-method="remoteMethod2"
                    :loading="state.loadding"
                >
                  <el-option
                      v-for="item in state.studentList2"
                      :key="item.id"
                      :label="item.stuName + '-' + item.stuNum"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="指导教师" prop="teacherIds">
                <el-select
                    v-model="state.editForm.teacherIds"
                    multiple
                    placeholder="请选择"
                    style="width: 240px"
                    :multiple-limit="3"
                >
                  <el-option
                      v-for="item in state.teacherList"
                      :key="item.id"
                      :label="item.teacherName"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-form label-width="150" label-position="top">
          <el-form-item label="上传材料：" label-position="top" label-width="150">
            <div class="uploadBox">
              <FileUpload
                  :multiple="false"
                  :limit="1"
                  :fileSize="20"
                  :fileType="['pdf']"
                  v-model="state.editForm.acFile"
                  :is-show-tip="false"
              />
              <p class="tip">论文上传材料要求：包括“期刊首页、目录、正文全文”的 <span>pdf</span> 文件，或者“录用通知/证明”扫描后的 <span>pdf</span> 文件。</p>
            </div>
          </el-form-item>
        </el-form>

        <div class="footer">
          <el-button @click="handleClose">返回</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.uploadBox {
  margin-left: 50px;
}

.footer {
  text-align: center;
}
.tip{
  font-size: 12px;
  margin: 0;
  span{
    color: red;
  }
}
</style>
